package gfx;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;

/**
 * Loads the images for the program.
 * 
 * @author ruben.ortlam
 */
public class ImageLoader {
	
	public BufferedImage mineOn = load("/gfx/MineOn.png");
	public BufferedImage mineOff = load("/gfx/MineOff.png");
	
	/**
	 * Loads the image file at the given path to a BufferedImage.
	 * 
	 * @param path The path to the image file.
	 * @return The BufferedImage if the file was valid, null otherwise.
	 */
	public BufferedImage load(String path) {
		try {
			return ImageIO.read(getClass().getResource(path));
		} catch(IOException e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	/**
	 * Splits an image to an image map with the given parameters.
	 * 
	 * @param map The BufferedImage from which the map will be loaded.
	 * @param sizeX The x-coordinate of the amount of tiles to be loaded.
	 * @param sizeY The y-coordinate of the amount of tiles to be loaded.
	 * @param width The width of a part of the image map.
	 * @param height The height size of a part of the image map.
	 * @return The 2-Dimensional BufferedImage Array containing the split image, null if an error occured.
	 */
	public BufferedImage[][] splitImageMap(BufferedImage map, int sizeX, int sizeY,
			int width, int height) {
		if(sizeX <= 0 || sizeY <= 0 || width <= 0 || height <= 0 || 
				sizeX * width > map.getWidth() || sizeY * height > map.getHeight()) {
			return null;
		}
		
		BufferedImage[][] images = new BufferedImage[sizeX][sizeY];
		
		for(int x = 0; x < sizeX; x++) {
			for(int y = 0; y < sizeY; y++) {
				images[x][y] = map.getSubimage(x * width, y * height, width, height);
			}
		}
		
		return images;
	}
	
	/**
	 * Splits an image to an image map with the given parameters.
	 * 
	 * @param map The BufferedImage from which the map will be loaded.
	 * @param width The width of a part of the image map.
	 * @param height The height size of a part of the image map.
	 * @return The 2-Dimensional BufferedImage Array containing the split image, null if an error occured.
	 * @author lueko.voss
	 */
	public BufferedImage[][] splitImageMap(BufferedImage map, int width, int height) {
	    int sizeX = map.getWidth() / width;
	    int sizeY = map.getHeight() / height;
	    
        BufferedImage[][] images = new BufferedImage[sizeX][sizeY];
        
        for(int x = 0; x < sizeX; x++) {
            for(int y = 0; y < sizeY; y++) {
                images[x][y] = map.getSubimage(x * width, y * height, width, height);
            }
        }
        
        return images;
    }
}
